<?php
/*
* Kusht Engine.
* ----
* The MIT License
* Copyright (c) 2010 Andrew Tutt
* ----
*/

/* JSON Connector Class
*
* Should only hold connection-related information regarding a connected user
* in a JSON transaction environment
*/

class JSONConnector {
public $id; 		/* This is a Connection ID, not a Game Object ID */
public $socket; 	/* This is the User's Socket */
public $server;		/* This is the Connector's Server */
public $handshake;  /* This is the User's Handshake Status */
public $user;		/* This is the user who owns this connection */
public $loggedin;   /* Is the Connector In the Stream or Entering It? */
// I.E. Is this person on their own thread or in the main thread?

private $buffer; /* For use with telnet */
	
function __construct($server, $socket) {
	$this->id 			= Connector::$top_id++;
	$this->loggedin 	= false;
	$this->handshake 	= false;
	$this->server 		= $server;
	$this->socket 		= $socket;
	$this->buffer		= "";
}

function send($msg, $wrapper = TEXT) {
	$data = array(TEXT=>array($wrapper,$msg));
	$this->send_data($data);
}

function send_data($data) {
	$msg = json_encode($data);
	$msg = $this->wrap($msg);
	if (@socket_write($this->socket,$msg,strlen($msg))===FALSE) {
		$this->disconnect();
	}
}

function show_welcome_screen() {
	loginMngr::show_welcome_screen($this);
}

function handle_input($buffer) {
	if($this->handshake===false) {
		$this->dohandshake($buffer);
		$this->show_welcome_screen();
		loginMngr::$loginSessions += array($this->id=>new loginSession($this));
		return;
	}
	
	$msg = $this->unwrap($buffer);
	
	if($this->loggedin===false) {
		loginMngr::$loginSessions[$this->id]->login($msg);
		return;
	}
	
	CmdHandler::splitCmd($this->user,$msg); /* This Data is Now Part of the Game */
}

function disconnect() {
	if($this->loggedin===false) {
		echo($this->socket." UNEXPECTED DISCONNECT.\n");
	}
	
	$this->server->disconnect($this->id,$this->socket); 
}

function wrap($msg="")	{ return chr(0).$msg.chr(255); 			}
function unwrap($msg=""){ return substr($msg,1,strlen($msg)-2); }

function dohandshake($buffer){
	list($resource,$host,$origin) = $this->getheaders($buffer);
	$upgrade	= "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
							"Upgrade: WebSocket\r\n" .
							"Connection: Upgrade\r\n" .
							"WebSocket-Origin: " . $origin . "\r\n" .
							"WebSocket-Location: ws://" . $host . $resource . "\r\n" .
							"\r\n";
	socket_write($this->socket,$upgrade.chr(0),strlen($upgrade.chr(0)));
	$this->handshake=true;
}

function getheaders($req){
	$r=$h=$o=null;
	if(preg_match("/GET (.*) HTTP/",	$req,$match))	{ $r=$match[1]; }
	if(preg_match("/Host: (.*)\r\n/",	$req,$match))	{ $h=$match[1]; }
	if(preg_match("/Origin: (.*)\r\n/",	$req,$match))	{ $o=$match[1]; }
	return array($r,$h,$o);
}

}

?>